package com.hy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.Result.ResponseResult;
import com.hy.mapper.AppOrderMapper;
import com.hy.pojo.order.AppOrder;
import com.hy.wxConfig.MyWxPayUtil;
import com.hy.wxConfig.WeChatPayQRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class AppOrderServiceImpl implements AppOrderService {
    @Autowired
    private AppOrderMapper appOrderMapper;

    //提交预约 生成二维码
    @Override
    public ResponseResult create(AppOrder appOrder) {
        //参数校验
        if (appOrder == null || appOrder.getPhone() == null || appOrder.getPhone().length() != 11 || appOrder.getOrderDate() == null || appOrder.getSetmealId() == null) {
            return ResponseResult.errorResult(400, "请添加正确信息!");
        }
        try {
            // 示例调用
            String string = UUID.randomUUID().toString().replace("-", "").substring(0, 32);
            String qrCode = MyWxPayUtil.generateQrCode("速度向-》>高雨航付款",string, "1");
            String s = WeChatPayQRCodeUtil.generateWeChatPayQrCodeBase64(qrCode);
            Map<String,Object> map = new HashMap<>();
            map.put("QR code image", s);
            map.put("Order number", string);
            //订单编号
            appOrder.setOrderMember(string);
            //到诊状态
            appOrder.setOrderStatus(AppOrder.ORDERSTATUS_NO);
            //支付方式
            appOrder.setOrderType(AppOrder.ORDERTYPE_WEIXIN);
            //支付状态
            appOrder.setZfStatus(AppOrder.ZHIFU_NO);
            System.err.println(appOrder);

            appOrderMapper.insert(appOrder);
            return ResponseResult.okResult(200, "已生成二维码", map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.err.println(appOrder);
        return ResponseResult.errorResult(400, "生成二维码失败!");
    }

    //检查支付状态
    @Override
    public ResponseResult checkPayStatus(String no) throws InterruptedException {
        System.err.println(no);
        //根据订单号查询订单状态
        LambdaQueryWrapper<AppOrder> la = new LambdaQueryWrapper<>();
        la.eq(AppOrder::getOrderMember, no);
        AppOrder appOrder = appOrderMapper.selectOne(la);

        String status = "";
        int i = 0;
        // 设置最大重试次数（1分钟最多20次）
        int maxRetries = 20;

        // 获取当前时间戳
        long startTime = System.currentTimeMillis();
        // 设定最大执行时间为60秒（60000毫秒）
        long maxTime = 60000;

        // 循环检测支付状态
        while (i < maxRetries) {
            // 检查是否超时，超时则退出
            if (System.currentTimeMillis() - startTime > maxTime) {
                System.err.println("支付超时");
                appOrder.setZfStatus(AppOrder.ZHIFU_CHAOSHI);
                appOrderMapper.updateById(appOrder);
                return ResponseResult.errorResult(400, "TIMEOUT");
            }

            try {
                status = MyWxPayUtil.checkOrder(no);
                if ("SUCCESS".equals(status)) {
                    //根据订单编号查询订单信息
                    // 更新订单状态为已支付
                    appOrder.setZfStatus(AppOrder.ZHIFU_YES);
                    appOrderMapper.updateById(appOrder);

                    System.err.println("支付成功");
                    return ResponseResult.errorResult(200,"SUCCESS");
                }
            } catch (Exception e) {
                // 处理异常，例如网络超时等
                System.err.println("查询支付状态失败: " + e.getMessage());
                return ResponseResult.errorResult(400, "ERROR");
            }

            // 每次检查间隔3秒
            Thread.sleep(3000);
            i++;
        }

        // 如果超时则返回TIMEOUT
        System.err.println("支付超时");
        return ResponseResult.errorResult(400, "TIMEOUT");
    }
}
